#pragma once

#include<iostream>
#include<unistd.h>
#include<string>
#include<cstring>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include"Log.hpp"

enum
{
    SocketErr = 2,
    BindErr,
    ListenErr,
};


const int backlog = 10;

class Sock
{
public:
    Sock()
    {}
    ~Sock()
    {}
public:
    // 创建套接字
    void Socket()
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket err, %s: %d", strerror(errno), errno);
            exit(SocketErr);
        }
        int opt = 1;
        setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    }

    // 绑定套接字
    void Bind(uint16_t port)
    {
        //填充套接字信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family =  AF_INET;
        local.sin_port = htons(port);//主机转网络
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(sockfd_, (const sockaddr*)&local, sizeof(local)) < 0) 
        {
            lg(Fatal, "bind err, %s: %d", strerror(errno), errno);
            exit(BindErr);
        }
    }

    //监听
    void Listen()
    {
        if(listen(sockfd_, backlog) < 0)
        {
            lg(Fatal, "listen err, %s: %d", strerror(errno), errno);
            exit(ListenErr);
        }
    }

    //获取链接
    int Accept(std::string &clientip, uint16_t &clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int newfd = accept(sockfd_, (struct sockaddr*)&peer, &len);
        if(newfd < 0)
        {
            lg(Warning, "listen err, %s: %d", strerror(errno), errno);
            return -1;
        }

        //获取客户端信息
        char ipstr[32];
        //网络转字符串地址
        inet_ntop(AF_INET, &peer.sin_addr, ipstr, sizeof(ipstr));

        clientip = ipstr;
        clientport = ntohs(peer.sin_port);
        return newfd;
        
    }
    // 链接
    int Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        //填充套接字信息
        server.sin_family = AF_INET;
        server.sin_port = htons(port);//主机转网络
        inet_pton(AF_INET, ip.c_str(), &(server.sin_addr));//字符ip转网络ip

        int n = connect(sockfd_, (const struct sockaddr*)&server, sizeof(server));
        if(n == -1)
        {
            std::cerr << "connect to " << ip << ":" << port << "error" << std::endl;
            return false;
        }
        return true;
    }

    void Close()
    {
        close(sockfd_);
    }
    int Fd()
    {
        return sockfd_;
    }
private:
    int sockfd_;
};
